package top.infopub.mgr.mkt.service.impl;


import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import com.alibaba.fastjson.JSON;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import top.infopub.enums.mkt.ProjectFileTypeEnum;
import top.infopub.enums.sg.CoopInfoTypesEnums;
import top.infopub.generic.GenericDao;
import top.infopub.generic.GenericServiceImpl;
import top.infopub.mgr.common.vo.RspVo;
import top.infopub.mgr.flow.cnst.FlowTemplateEnum;
import top.infopub.mgr.flow.service.WsFlowProcessService;
import top.infopub.mgr.mkt.dao.*;
import top.infopub.mgr.mkt.domain.PreProjectDomain;
import top.infopub.mgr.mkt.domain.ProjectDomain;
import top.infopub.mgr.mkt.jsonvo.CollectJsonVo;
import top.infopub.mgr.mkt.service.BaseLineService;
import top.infopub.mgr.mkt.service.PreProjectService;
import top.infopub.mgr.mkt.vo.CollectProjectVo;
import top.infopub.mgr.mkt.vo.InvestmentInfoVo;
import top.infopub.mgr.mkt.vo.ItemNameVo;
import top.infopub.mgr.mkt.vo.PreProjectVo;
import top.infopub.mgr.sg.service.CoopInfoService;
import top.infopub.model.mkt.*;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import top.infopub.model.sg.CoopInfo;
import top.infopub.security.vo.AuthorizationVO;
import top.infopub.util.IdFactory;


@Service
public class PreProjectServiceImpl extends GenericServiceImpl<PreProject, String> implements PreProjectService {

    @Autowired
    private PreProjectDao preProjectDao;

    @Autowired
    private PreProjectCoopDao preProjectCoopDao;

    @Autowired
    private PreProjectSubDao preProjectSubDao;

    @Autowired
    private PreProjectAttDao preProjectAttDao;

    @Autowired
    private WsFlowProcessService wsFlowProcess;

    @Autowired
    private ProjectInfoDao projectInfoDao;

    @Autowired
    private AfterSummaryCoopDao afterSummaryCoopDao;

    @Autowired
    private ProjectSubInfoDao projectSubInfoDao;

    @Autowired
    private ProjectRiskDao projectRiskDao;

    @Autowired
    private ProjectAttachmentDao projectAttachmentDao;
    @Autowired
    private BaseLineService baseLineService;
    @Autowired
    private CoopInfoService coopInfoService;

    @Override
    public GenericDao<PreProject, String> getDao() {
        return preProjectDao;
    }

    @Override
    public Page<ProjectDomain> selectPageByDomainWhere(Page<ProjectDomain> page,
                                                       CollectProjectVo collectProjectVo) {
        //处理时间范围
        if (!StringUtils.isEmpty(collectProjectVo.getDates())) {
            String[] splitTime = collectProjectVo.getDates().split("~");
            SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd");
            try {
                collectProjectVo.setEndDate(format.parse(splitTime[1]));
                collectProjectVo.setStartDate(format.parse(splitTime[0]));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        return (Page<ProjectDomain>)preProjectDao.selectByDomain(collectProjectVo);
    }

    @Override
    public Page<PreProjectDomain> selectMyCheckByDomainWhere(Page<PreProjectDomain> page,
                                                             PreProjectVo preProjectVo) {
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        return (Page<PreProjectDomain>)preProjectDao.selectMyCheckByDomainWhere(preProjectVo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addPreProject(PreProject preProject, List<PreProjectCoop> preProjectCoops,
                              List<PreProjectSub> preProjectSubs,
                              List<PreProjectAtt> preProjectAtts) {
        //插入预立项记录
        preProjectDao.insertById(preProject);

        //批量插入联合体单位
        if (CollectionUtils.isNotEmpty(preProjectCoops)) {
            preProjectCoopDao.insertByBatch(preProjectCoops);
        }

        //批量插入联合体单位
        if (CollectionUtils.isNotEmpty(preProjectSubs)) {
            preProjectSubDao.insertByBatch(preProjectSubs);
        }

        //批量插入附件
        if (CollectionUtils.isNotEmpty(preProjectAtts)) {
            preProjectAttDao.insertByBatch(preProjectAtts);
        }

        // 注意 这里根据不同的业务分支判断条件 获得不同enum
        FlowTemplateEnum templateEnum = FlowTemplateEnum.MKT_PRE_PROJECT;
        // 处理工作流数据
        wsFlowProcess.launch(templateEnum, preProject.getId(), preProject.getProcessId(), null);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void editPreProject(PreProject preProject, List<PreProjectCoop> preProjectCoops, List<PreProjectSub> preProjectSubs, List<PreProjectAtt> fileAtts, String submitType) {
        //编辑预立项记录
        preProjectDao.updateByIdSelective(preProject);
        preProjectCoopDao.deleteByProjectId(preProject.getId());
        preProjectSubDao.deleteByProjectId(preProject.getId());
        preProjectAttDao.deleteByProjectId(preProject.getId());

        //批量插入联合体单位
        if (CollectionUtils.isNotEmpty(preProjectCoops)) {
            preProjectCoopDao.insertByBatch(preProjectCoops);
        }

        //批量插入联合体单位
        if (CollectionUtils.isNotEmpty(preProjectSubs)) {
            preProjectSubDao.insertByBatch(preProjectSubs);
        }

        //批量插入附件
        if (CollectionUtils.isNotEmpty(fileAtts)) {
            preProjectAttDao.insertByBatch(fileAtts);
        }

        if("2".equalsIgnoreCase(submitType)){
            preProject=preProjectDao.selectById(preProject.getId());
            PreProject project=new PreProject();
            project.setId(preProject.getId());
            project.setProcessStatus("1");//审判中
            preProjectDao.updateByIdSelective(project);
            // 注意 这里根据不同的业务分支判断条件 获得不同enum
            FlowTemplateEnum templateEnum = FlowTemplateEnum.MKT_PRE_PROJECT;
            // 处理工作流数据
            wsFlowProcess.launch(templateEnum, preProject.getId(), preProject.getProcessId(), null);

        }

    }

    @Override
    public PreProjectVo selectById(String id) {
        return preProjectDao.selectById(id);
    }

    @Override
    public List<PreProject> selectUsableSetupPreProject() {
        return preProjectDao.selectUsableSetupPreProject();
    }

    @Override
    public List<PreProject> selectPreProject(String proCode) {
        return preProjectDao.selectPreProject(proCode);
    }

    @Override
    public PreProjectDomain queryByProCode(String proCodes) {
        return preProjectDao.queryByProCode(proCodes);
    }

    @Override
    public List<PreProject> getPreProjectWithStaff(String proCode, String hrStaffMktId) {
        return preProjectDao.getPreProjectWithStaff(proCode, hrStaffMktId);
    }

    @Override
    public List<PreProject> selectNotBindOrg() {
        return preProjectDao.selectNotBindOrg();
    }

    @Override
    public List<PreProject> selectByProName(String proName) {
        return preProjectDao.selectByProName(proName);
    }

    @Override
    public List<PreProject> selectByProCode(String proCode) {
        return null;
    }

    @Override
    public CollectJsonVo queryDetailById(String id) {
        CollectJsonVo collectJsonVo = new CollectJsonVo();
        //基础信息
        PreProject preProject = preProjectDao.selectByPrimaryKey(id);
        ProjectInfo projectInfo = projectInfoDao.findTailByProCode(preProject.getProCode());
        projectInfo.setProcessId(preProject.getProcessId());
        projectInfo.setPreId(preProject.getId());
        collectJsonVo.setProjectInfo(projectInfo);
        //项目合作单位信息
        collectJsonVo.setSummaryCoops(afterSummaryCoopDao.querySummaryCoopList(projectInfo.getProCode(), 0));
        //项目投资构成信息
        ProjectSubInfo projectSubInfo = projectSubInfoDao.queryByProCode(projectInfo.getProCode());
        if (projectSubInfo != null) {
            if (StringUtils.isNotBlank(projectSubInfo.getTitleJson())) {
                collectJsonVo.setItemName(JSON.parseArray(projectSubInfo.getTitleJson(), ItemNameVo.class));
            }
            if (StringUtils.isNotBlank(projectSubInfo.getContentJson())) {
                collectJsonVo.setInvestmentInfoVos(JSON.parseArray(projectSubInfo.getContentJson(), InvestmentInfoVo.class));
            }
        }
        //项目风险信息
        collectJsonVo.setRiskTable(projectRiskDao.selectByProCode(projectInfo.getProCode()));
        //底线标准情况
        collectJsonVo.setStandardTable(baseLineService.checkIsSatisfy(projectInfo.getProCode()));
        //附件信息表
        List<ProjectAttachment> projectAttaList = projectAttachmentDao.queryByWhere(projectInfo.getProCode(), ProjectFileTypeEnum.FILE_TYPE2.getCode(), null);
        collectJsonVo.setFileAtt(fileAttaListToArray(projectAttaList));
        //合作单位信息
        List<CoopInfo> coopInfoList = coopInfoService.queryByTypes(CoopInfoTypesEnums.OWNER, 1);
        collectJsonVo.setCoopInfoList(coopInfoList);

        return collectJsonVo;
    }
    public String[] fileAttaListToArray(List<ProjectAttachment> list) {
        if (list == null || list.size() <= 0) return null;
        String[] attaArr = new String[list.size()];
        int index = 0;
        for (ProjectAttachment pa : list) {
            StringBuffer tmp = new StringBuffer();
            tmp.append(pa.getSubTypes());
            tmp.append("|");
            tmp.append(pa.getFileName());
            tmp.append(pa.getFileSuffix());
            tmp.append("|");
            tmp.append(IdFactory.getUUIDSerialNumber());
            tmp.append("|");
            tmp.append(pa.getFilePath());
            attaArr[index] = tmp.toString();
            index++;
        }
        return attaArr;
    }


//    @Override
//    public void saveAll(ProjectInfo projectInfo, PreProject preProject, List<AfterSummaryCoop> summary, ProjectSubInfo proSubInfo, List<ProjectRisk> riskList, List<ProjectAttachment> attachmentList, AuthorizationVO userDtl) {
//
//        projectInfo.setUptBy(userDtl.getId());
//        projectInfo.setUptTime(new Date());
//        //处理项目基础信息
//        projectInfoDao.modifyProjectInfoBySeletive(projectInfo);
//        //处理预立项信息
//        preProjectDao.updateById(preProject.getId());
//
//        //更新项目合作单位
//        afterSummaryCoopDao.deleteByProCode(projectInfo.getProCode());
//        afterSummaryCoopDao.insertByBatch(summary);
//
//        //更新子项表格信息数据
//        ProjectSubInfo psi = projectSubInfoDao.queryByProCode(projectInfo.getProCode());
//        if (psi == null) {
//            proSubInfo.setAddBy(userDtl.getId());
//            proSubInfo.setAddTime(new Date());
//            projectSubInfoDao.insert(proSubInfo);
//        } else {
//            proSubInfo.setId(psi.getId());
//            projectSubInfoDao.modifyById(proSubInfo);
//        }
//
//        //更新风险信息
//        projectRiskDao.deleteByProCode(projectInfo.getProCode());
//        projectRiskDao.insertBatch(riskList);
//
//        //更新附件信息
//        projectAttachmentDao.deleteByWhere(projectInfo.getProCode(), ProjectFileTypeEnum.FILE_TYPE4.getCode(), null);
//        if (attachmentList != null && attachmentList.size() > 0) {
//            projectAttachmentDao.insertBatch(attachmentList);
//        }
//
//    }

}
